<template>
    <section>
        <!--工具条-->

        <div class="section-content clearfix">
            <el-col :span="24" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="filters">
                    <el-form-item>
                        <el-input v-model="filters.name" placeholder="设备固件名称" @keyup.enter.native="getUsers()"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="filters.coded" placeholder="设备编码" @keyup.enter.native="getUsers()"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button :type="buttonColor" v-on:click="getUsers">查询</el-button>
                    </el-form-item>
                    <el-form-item v-if="menubt.indexOf('/device_lower_upgrade/post')>-1">
                        <el-button :type="buttonColor" @click="handleAdd">新增</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <!--列表-->
            <el-table :data="query" highlight-current-row v-loading="listLoading" @selection-change="selsChange" :header-row-style="{backgroundColor: titleColor}" style="width: 100%;">
      
                <el-table-column align="center" type="index" label="序号"  width="80":index="indexMethod" >
                </el-table-column>
                <el-table-column align="center" prop="name" label="名称">

                    <template scope="scope">

                        <span class="pb-name" @click="details(scope.$index, scope.row)">{{scope.row.name}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="coded" label="设备固件编码">
                </el-table-column>
                <el-table-column align="center" prop="version" label="设备固件版本">
                </el-table-column>
                <el-table-column align="center" prop="fileSize" label="大小">
                </el-table-column>
                <el-table-column align="center" prop="remark"  label="备注">
                </el-table-column>
                <el-table-column align="center" label="当前状态">
                    <template scope="scope">

                        <span v-if="scope.row.state==2">已停用</span>
                        <span v-if="scope.row.state==1">已启用</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="设备固件设置" v-if="menubt.indexOf('/device_lower_upgrade/put')>-1">
                    <template scope="scope">

                        <el-button v-if="scope.row.state==2" title="点击启用" size="small" @click="stateput( scope.row)"
                            :type="buttonColor" plain>启用</el-button>
                        <el-button v-if="scope.row.state==1" title="点击停用" size="small" type="small" @click="stateput( scope.row)"
                            plain>停用</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" v-if="menubt.indexOf('/device_lower_upgrade/delete')>-1">
                    <template scope="scope">
                        <i @click="handleEdit(scope.$index, scope.row)" title="编辑" icon="el-icon-edit" circle class="pb-icon icon-edit"></i>
                        <i @click="handleDel(scope.$index, scope.row)" icon="el-icon-delete" circle title="删除" class="pb-icon icon-delete"></i>

                    </template>
                </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar">
                <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->
                <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total"
                    style="float:right;">
                </el-pagination>
            </el-col>
        </div>
        <!--编辑界面-->
        <el-dialog title="编辑" v-show="editFormVisible" v-model="editFormVisible" :custom-class="dialogTitleColor" @close="editFormVisible=false">
            <div slot="footer" style="text-align: left; ">
                <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="editForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    
                    <el-form-item label="备注"   >
                        <el-input type="textarea" v-model="editForm.remark"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:right;">
                    <el-button @click.native="editFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="editSubmit" :loading="editLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-show="addFormVisible" v-model="addFormVisible" :custom-class="dialogTitleColor" @close="addFormVisible=false">
            <div slot="footer" style="text-align: left; ">

                <el-form :model="addForm" label-width="110px" :rules="addFormRules" ref="addForm">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="addForm.name" auto-complete="off" class="grade"></el-input>
                    </el-form-item>
                    <el-form-item label="设备固件编码" prop="softCode">
                        <el-input v-model="addForm.softCode" type="number" auto-complete="off" class="grade" :disabled="disableditem"></el-input>
                        (填上固件编码后四位)
                    </el-form-item>
                    <el-form-item label="设备固件版本" prop="version1">
                        <el-input v-model="addForm.version1" auto-complete="off" class="grade" :disabled="disableditem"></el-input>
                    </el-form-item>
                    <el-form-item label="传输类型" prop="serverType">
                        <!-- <el-select v-model="addForm.serverType" @change="serverscade()"> -->
                        <el-select v-model="addForm.serverType">
                            <el-option v-for="item in modellist" :label="item.name" :value="item.modelId"></el-option>
                            <!-- <el-option label="http" value="0"></el-option>
                            <el-option label="ftp" value="1"></el-option> -->
                        </el-select>
                        <!-- <el-radio-group v-model="addForm.serverType" @change="serverscade()">
                            <el-radio label="0">http</el-radio>
                            <el-radio label="1">ftp</el-radio>
                        </el-radio-group> -->
                    </el-form-item>
                    <el-form-item label="设备固件上传">

                        <el-input v-model="fileList.name" auto-complete="off" class="grade" placeholder="文件名" :disabled="true"></el-input>
                        <!-- <el-input v-model="fileList.dir" auto-complete="off" class="grade" placeholder="文件路径" :disabled="true"></el-input> -->
                        <el-upload class="upload-demo" :headers="fileList" multiple :limit="1" :on-exceed="handleExceed"
                            :on-change="handleChange" action="/api/auth/soft/upload" accept=".env"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :file-list="fileitem">
                            <el-button size="small" :type="buttonColor">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传env文件，且不超过100MB</div>
                        </el-upload>
                    </el-form-item>
                    <!-- <el-form-item label="size" prop="size">
                        <el-input v-model="addForm.fileSize" auto-complete="off" class="grade"></el-input>
                    </el-form-item> -->

                    <el-form-item label="启用状态" prop="state">
                        <el-radio v-model="addForm.state" label="1">启用</el-radio>
                        <el-radio v-model="addForm.state" label="2">停用</el-radio>
                    </el-form-item>

                    <el-form-item label="备注"  >
                        <el-input v-model="addForm.remark" type="textarea" auto-complete="off" class="grade"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button @click.native="addFormVisible = false">取消</el-button>
                    <el-button :type="buttonColor" @click.native="addSubmit" :loading="addLoading">提交</el-button>
                </div>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    // import util from './../common/js/util'
    //import NProgress from 'nprogress'
    import {
        device_upgrade_query,
        device_upgrade_post,
        device_upgrade_get,
        device_upgrade_delete,
        device_upgrade_put,
        device_model_query
    } from './../../../api/api';

    export default {
        data() {
            return {
                disableditem: false,
                fileitem: [],
                fileList: {
                    softCode: '',
                    version: '',
                    name: '',
                    dir: 'http/SoftWave',
                    token: JSON.parse(localStorage.getItem('key'))
                },
                modellist:[],
                filters: {
                    name: '',

                    coded: ''
                },
                file: '',
                query: [],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [], //列表选中列
                editFormVisible: false, //编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [{
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    },{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }]
                },
                //编辑界面数据
                editForm: {
                    id: '',
                    type: '',
                    name: '',
                    englishName: '',
                    parentId: '',
                    path: '',
                    icon: '',
                    status: '',
                    priority: '',
                    createTime: ''
                },

                addFormVisible: false, //新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [{
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    },{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                    // softCode: [{
                    //     required: true,
                    //     message: '请输入设备固件编码',
                    //     trigger: 'blur'
                    // }],
                    // version1: [{
                    //     required: true,
                    //     message: '请输入设备固件版本',
                    //     trigger: 'blur'
                    // }],

                },
                //新增界面数据
                addForm: {
                    name: '',
                    coded: '',
                    version: '',
                    fileSize: '',
                    type: '2',
                    state: '1',
                    serverType: '1',
                    remark: '',
                    ftpPath: '',
                    Path: '',
                    softCode:'',
                    version1:''
                }

            }
        },
        computed:{
            buttonColor(){
                return this.$store.state.buttonColor
            },
            titleColor(){
                return this.$store.state.titleColor
            },
            dialogTitleColor(){
                return this.$store.state.dialogTitleColor
            },
        },
        methods: {
            indexMethod(index) {
                console.log(this.page)
                let num = (this.page - 1) * 10 + index + 1;
                return num;
            },
            serverscade() {
                if (this.addForm.serverType == 0) {
                    this.fileList.dir = "http/SoftWave"
                } else {

                    this.fileList.dir = "ftp/SoftWave"
                }
            },
            details: function (index, row) {
                sessionStorage.setItem('communicate_details', row.id)
                this.$router.push({
                    path: '/devices/communicate/details'
                })
            },
            stateput(s) {
                if (s.state == 1) {
                    s.state = 2;
                } else {
                    s.state = 1;
                }
                let para = Object.assign({}, s);

                device_upgrade_put(para).then((res) => {

                     this.begCode(res.code,res.message);
                    if (res.code == 0) {
                        this.editLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '状态修改成功',
                            type: 'success'
                        });
                        this.$refs['editForm'].resetFields();
                        this.editFormVisible = false;
                        this.getUsers();
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'warning'
                        });
                    }
                });
            },
            //性别显示转换
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件`);
            },
            handleAvatarSuccess(res, file) {
                console.log(file.type);

                this.begCode(res.code, res.message);
                if (res.code != 0) {
                    this.fileitem = [];
                }
                this.addForm.path = res.data.path;
                this.addForm.ftpPath = res.data.ftpPath;
                this.disableditem = true;
            },
            beforeAvatarUpload(file) {
                console.log(typeof file.name)
                let name = file.name;

                console.log(name);
                var index = name.lastIndexOf("\.");
                this.fileList.name = name.substring(0, index);
                this.addForm.fileSize = file.size;
                var patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;

                if (patrn.test(this.fileList.name)) {

                    this.$message.error('上传文件名字不能带有填中文!');
                    return false;
                }
                console.log(this.fileList.name)
                  
                this.fileList.softCode=this.addForm.softCode;
                this.fileList.version=this.addForm.version1;
                if (!this.fileList.softCode || !this.fileList.version || !this.fileList.name || !this.fileList.dir) {

                    this.$message.error('上传文件信息填写完整!');
                    return false;
                }
                if (this.fileList.softCode.length != 4) {
                                this.$message({
                                    message: '编码只能为4位',
                                    type: 'warning'
                                });
                                return false
                            }
                const isBIN = file.type === 'application/octet-stream';
                let tp = true;
                const isLt2M = file.size / 1024 / 1024 < 100;
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 100MB!');
                }
                return tp && isLt2M;
            },
            handleChange(file, fileList) {},
            formatSex: function (row, column) {
                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            //获取菜单列表
            getUsers() {
                if (this.menubt.indexOf('/device_lower_upgrade/query') == -1) {
                    this.$message({
                        message: '没有查询设备固件的权限',
                        type: 'warning'
                    });
                    return false;
                }
                let para = {
                    pageNo: this.page,
                    pageSize: 10,
                    name: this.filters.name,

                    coded: this.filters.coded,
                    type: 2
                };
                this.listLoading = true;
                //NProgress.start();
                device_upgrade_query(para).then((res) => {

                     this.begCode(res.code,res.message);
                    this.total = res.data.totalCount;
                    this.query = res.data.list;
                    this.listLoading = false;
                    this.page=res.data.pageNo;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {

                this.$confirm('确认删除该固件吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        idList: [row.id]
                    };
                    device_upgrade_delete(para).then((res) => {

                         this.begCode(res.code,res.message);
                        if (res.code == 0) {

                            this.listLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getUsers();

                        } else {
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            //显示新增界面
            handleAdd: function () {

                this.disableditem = false;
                this.addFormVisible = true;
                this.fileitem = [];
                this.fileList = {
                    softCode: '',
                    version: '',
                    name: '',
                    dir: 'http/SoftWave',
                    token: JSON.parse(localStorage.getItem('key'))
                };
                this.addForm = {
                    name: '',
                    coded: '1',
                    version: '',
                    fileSize: '',
                    type: '2',
                    state: '1',
                    serverType: '1',
                    remark: '',
                    ftpPath: '',
                    path: ''
                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);

                            device_upgrade_put(para).then((res) => {

                                 this.begCode(res.code,res.message);
                                if (res.code == 0) {
                                    this.editLoading = false;
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                } else {
                                    this.$message({
                                        message: res.message,
                                        type: 'warning'
                                    });
                                }
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            console.log(this.addForm)
                            
                            this.fileList.softCode=this.addForm.softCode;
                            if (this.fileList.softCode.length != 4) {
                                this.$message({
                                    message: '编码只能为4位',
                                    type: 'warning'
                                });
                                return false
                            }
                            if (!this.addForm.path) {
                                this.$message({
                                    message: '请先上传文件',
                                    type: 'warning'
                                });
                                return false
                            }
                            this.addLoading = true;
                            //NProgress.start();
                
                            this.fileList.softCode=parseInt(this.fileList.softCode);
                          this.fileList.version=this.addForm.version1;
                            this.addForm.coded = this.fileList.softCode;
                            this.addForm.version = this.fileList.version;
                            let para = Object.assign({}, this.addForm);

                            device_upgrade_post(para).then((res) => {

                                 this.begCode(res.code,res.message);
                                this.addLoading = false;

                                if (res.code == 0) {
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['addForm'].resetFields();
                                    this.addFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {
                        ids: ids
                    };
                    batchRemoveUser(para).then((res) => {
                         this.begCode(res.code,res.message);
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            this.menubt = localStorage.getItem('menubt');
            this.getUsers();
            let para = {
                pageNo: this.page,
                pageSize: 10,
            }
            device_model_query(para).then(res => {
                if(res.code == 0){
                    this.modellist = res.data.list
                }
            })
        }
    }
</script>

<style scoped>

</style>